﻿namespace dotnet_notes.Tools
{
    /// <summary>
    /// JWT 工具类
    /// </summary>
    public static class JwtTool
    {
        /// <summary>
        /// 获取令牌
        /// </summary>
        /// <param name="userData">用户信息(JSON)</param>
        /// <param name="token">令牌</param>
        /// <param name="expiresTime">令牌过期时间</param>
        public static void GetToken(string userData, out string token, out DateTime expiresTime)
        {
            var claims = new List<Claim>
            {
                new(ClaimTypes.UserData, userData)
            };

            expiresTime = DateTime.Now.AddMinutes(AppsettingsTool.Jwt.ExpiresMinute);

            var securityKey = new SymmetricSecurityKey
                (Encoding.UTF8.GetBytes(AppsettingsTool.Jwt.SigningKey));

            var securityToken = new JwtSecurityToken(
                AppsettingsTool.Jwt.Issuer,
                AppsettingsTool.Jwt.Audience,
                claims,
                expires: expiresTime,
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            );

            token = new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        /// <summary>
        /// 获取刷新令牌
        /// </summary>
        /// <param name="userData">用户信息(JSON)</param>
        /// <param name="token">刷新令牌</param>
        /// <param name="expiresTime">刷新令牌过期时间</param>
        public static void GetRefreshToken(string userData, out string token, out DateTime expiresTime)
        {
            var claims = new List<Claim>
            {
                new(ClaimTypes.UserData, userData)
            };

            expiresTime = DateTime.Now.AddDays(AppsettingsTool.RefreshJwt.ExpiresDay);

            var securityKey = new SymmetricSecurityKey
                (Encoding.UTF8.GetBytes(AppsettingsTool.RefreshJwt.SigningKey));

            var securityToken = new JwtSecurityToken(
                AppsettingsTool.RefreshJwt.Issuer,
                AppsettingsTool.RefreshJwt.Audience,
                claims,
                expires: expiresTime,
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            );

            token = new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        /// <summary>
        /// 验证刷新令牌
        /// </summary>
        /// <param name="token">要验证的令牌</param>
        /// <returns>令牌中的用户信息(JSON)</returns>
        public static string ValidateRefreshToken(string token)
        {
            var sk = Encoding.UTF8.GetBytes(AppsettingsTool.RefreshJwt.SigningKey);

            var handler = new JwtSecurityTokenHandler();
            var parms = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateIssuerSigningKey = true,
                ValidateLifetime = true,
                ValidIssuer = AppsettingsTool.RefreshJwt.Issuer,
                ValidAudience = AppsettingsTool.RefreshJwt.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(sk),
            };

            try
            {
                var claimsPrincipal = handler.ValidateToken(token, parms, out _);
                return claimsPrincipal.FindFirstValue(ClaimTypes.UserData);
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
